import axios from 'axios'
import { checkTimeOut } from '@/utils/checkTime'
import { useUsersStore } from '@/stores/user.js'

// 创建axios示例
const service = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      // 验证时间戳
      if (checkTimeOut()) {
        const userStrore = useUsersStore()
        // 退出登录
        userStore.loginOut()
        return Promise.reject(new Error("token is timeout"))
      }
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    console.error('请求拦截器错误', error)
    return Promise.reject(error)
  },
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {

    const res = response.data
    if (res.code && res.code !== 200) {
      console.log('业务错误', res.message)
      return Promise.reject(new Error(res.message))
    }
    return res
  },
  (error) => {
    const status = error.response?.status
    switch (status) {
      case 400:
        console.error('请求参数错误')
        break
      case 401:
        console.error('未授权或则token过期')
        break
      case 403:
        console.error('没有权限')
        break
      case 404:
        console.error('接口不存在')
        break
      case 500:
        console.error('服务器内部错误')
        break
    }
    return Promise.reject(error)
  },
)

export default service
